<template>
    <van-row>
     <van-col :span="24">
         <van-address-list
             v-model="store.state.chosenAddressId"
             :list="list"
             default-tag-text="默认"
             @add="onAdd"
             @edit="onEdit"
         >
         </van-address-list>
     </van-col>
    </van-row>
 </template>
 
 <script setup>
 import { showToast,showNotify } from 'vant';
 import { ref,onMounted,getCurrentInstance } from "vue";
 import store from '@/store';
 
 const {proxy} = getCurrentInstance(); 
 
 const list = ref([]);
 
 const userId = ref(null);
 const addressList = ref([]);
 
  const getAddressByUserId = ()=>{
     proxy.$axios({
         method:'get',
         url: '/address/user/'+userId.value
     }).then(res=>{
         let resultBean = res.data;
         if(resultBean.code == 200){
             addressList.value = resultBean.data;
             addressList.value.forEach(address=>{
                 list.value.push({
                     id: address.addressId,
                     name: address.contactName,
                     tel: address.contactTel,
                     address: address.address,
                 })
             })
             if(list.value.length>0){
                 //将该用户的第一个地址设为默认地址
                 list.value[0].isDefault = true;
                 //如果没有选中项
                 if(!store.state.chosenAddressId){
                     store.state.chosenAddressId = list.value[0].id;//设置第一个地址为选中项
                 }
             }
         }else{
             showNotify({message: resultBean.msg});
         }
     }).catch(error=>{
         showNotify({message: error.message});
     })
  }
 
  const onAdd = () => {
     proxy.$router.push('/main/addAddress');
  };
  const onEdit = (item, index) => showToast('编辑地址:' + index);
 
  onMounted(()=>{

let userJson = window.localStorage.getItem("loginUser");

if(!userJson){
  showNotify({message: '请先登录'});
  proxy.$router.push('/login');
  return;
}

let user = JSON.parse(userJson);


//获取用户id
userId.value = user.userId; //从本地存储获取

getAddressByUserId();

})
 
 </script>
 
 <style>
 </style>